import { NextRequest, NextResponse } from 'next/server';
import UserModel from '@/models/user';
import { authMiddleware, TokenPayload } from '@/utils/auth';

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }
    
    const decoded = authResult as TokenPayload;
    const userId = decoded.id;
    
    // 获取请求数据
    const body = await request.json();
    const { company_name, company_role } = body;
    
    if (!company_name) {
      return NextResponse.json(
        { error: '企业名称不能为空' },
        { status: 400 }
      );
    }
    
    try {
      // 更新用户为企业管理员
      const updateData = {
        is_company_admin: true,
        company: company_name,
        company_role: company_role || '管理员'
      };
      
      const updated = await UserModel.updateProfile(userId, updateData);
      
      if (!updated) {
        return NextResponse.json(
          { error: '设置企业管理员失败' },
          { status: 400 }
        );
      }
      
      // 检查企业是否已存在，如果不存在则创建
      const [companies] = await UserModel.query<any[]>(
        `SELECT id FROM companies WHERE name = ? LIMIT 1`,
        [company_name]
      );
      
      let companyId;
      
      if (!companies || companies.length === 0) {
        // 创建新企业
        const [result] = await UserModel.query<any>(
          `INSERT INTO companies (name, admin_user_id, created_at)
           VALUES (?, ?, NOW())`,
          [company_name, userId]
        );
        
        if (result && typeof result === 'object' && 'insertId' in result) {
          companyId = result.insertId;
        }
      } else {
        companyId = companies[0].id;
        
        // 更新企业管理员
        await UserModel.query(
          `UPDATE companies SET admin_user_id = ? WHERE id = ?`,
          [userId, companyId]
        );
      }
      
      // 获取更新后的用户资料
      const user = await UserModel.findById(userId);
      
      // 移除敏感信息
      const { password, ...userWithoutPassword } = user as any;
      
      return NextResponse.json(
        { 
          message: '设置企业管理员成功',
          user: userWithoutPassword,
          company_id: companyId
        },
        { status: 200 }
      );
    } catch (updateError) {
      console.error('设置企业管理员过程中发生错误:', updateError);
      return NextResponse.json(
        { error: `设置企业管理员时发生错误: ${(updateError as Error).message}` },
        { status: 500 }
      );
    }
  } catch (error) {
    console.error('设置企业管理员错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
